package com.shanyu.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.shanyu.dao.IArticleDao;
import com.shanyu.dao.IArticleTagDao;
import com.shanyu.dao.IClassificaDao;
import com.shanyu.dao.ITagDao;
import com.shanyu.dto.ArticleDto;
import com.shanyu.dto.ClassificaDto;
import com.shanyu.eo.ArticleEo;
import com.shanyu.eo.ArticleTagEo;
import com.shanyu.eo.ClassificaEo;
import com.shanyu.eo.TagEo;
import com.shanyu.service.IClassificaService;

@Service
public class ClassificaServiceImpl implements IClassificaService{
	
	@Autowired
	private IClassificaDao classificaDao;
	
	@Autowired
	private IArticleDao articleDao;
	
	@Autowired
	private IArticleTagDao articleTagDao;
	
	@Autowired
	private ITagDao tagDao;

	public List<ClassificaEo> getClassificaList() {
		// TODO Auto-generated method stub
		return classificaDao.select(new ClassificaEo());
	}

	public List<ClassificaDto> getClassificaArticle() {
		// TODO Auto-generated method stub
		List<ClassificaDto> res = new ArrayList<ClassificaDto>();
		//��ѯ������Ϣ
		List<ClassificaEo> classificaList = getClassificaList();
		if(!CollectionUtils.isEmpty(classificaList)){
			for(ClassificaEo eo : classificaList){
				ClassificaDto classificaDto = new ClassificaDto();
				BeanUtils.copyProperties(eo, classificaDto);
				classificaDto.setArticleList(getArticleListByClassificaId(eo.getId()));
				res.add(classificaDto);
			}
		}
		return res;
	}
	
	
	private List<ArticleDto> getArticleListByClassificaId(String classificaId){
		List<ArticleDto> res = new ArrayList<ArticleDto>();
		ArticleEo query = new ArticleEo();
		query.setClassificaId(classificaId);
		query.setStatus(2);
		List<ArticleEo> articleList =  articleDao.select(query);
		if(!CollectionUtils.isEmpty(articleList)){
			for(ArticleEo eo : articleList){
				ArticleDto dto = new ArticleDto();
				BeanUtils.copyProperties(eo, dto);
				dto.setTagList(getTagByArticleId(eo.getId()));
				res.add(dto);
			}
		}
		return res;
	}
	
	private List<TagEo> getTagByArticleId(String articleId){
		ArticleTagEo query = new ArticleTagEo();
		query.setArticleId(articleId);
		List<ArticleTagEo> articleTagList = articleTagDao.select(query);
		
		List<String> tagIds = new ArrayList<String>();
		if(!CollectionUtils.isEmpty(articleTagList)){
			for(ArticleTagEo articleTagEo : articleTagList){
				tagIds.add(articleTagEo.getTagId());
			}
		}
		
		return tagDao.selectByTagIds(tagIds);
	}

}
